package com.hospital.hospitalsystem.config;

import io.minio.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;


/**
 * @author qiancheng@cqxyy.net
 * @date 2022/11/7
 */
@Configuration
public class MinioConfig implements InitializingBean {
    @Value("${minio.url}")
    private String url;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;
    @Value("${minio.bucket}")
    private String bucket;

    public  MinioClient minioClient;


    @Override
    public void afterPropertiesSet() {
        minioClient = MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
    }


    /**
     * 判断桶是否为空
     *
     * @param bucketName
     * @return
     */
    @SneakyThrows
    public boolean bucketExists(String bucketName) {
        boolean flag = false;
        flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (flag) {
            return true;
        }
        return false;
    }

    /**
     * 创建桶
     *
     * @param bucketName
     * @return
     */
    @SneakyThrows
    public boolean makeBucket(String bucketName) {
        boolean flag = bucketExists(bucketName);
        if (!flag) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取所有桶的名称
     *
     * @return
     */
    @SneakyThrows
    public List<String> listBucketNames() {
        List<Bucket> bucketList = listBuckets();
        List<String> bucketListName = new ArrayList<>();
        for (Bucket bucket : bucketList) {
            bucketListName.add(bucket.name());
        }
        return bucketListName;
    }

    /**
     * 获取所有桶
     *
     * @return
     */
    @SneakyThrows
    public List<Bucket> listBuckets() {
        return minioClient.listBuckets();
    }

    @SneakyThrows
    public boolean removeBucket(String bucketName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<Item>> myObjects = listObjects(bucketName);
            for (Result<Item> result : myObjects) {
                Item item = result.get();
                //桶内不为空，则删除失败
                if (item.size() > 0) {
                    return false;
                }
            }
            //桶内为空，删除成功
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
            flag = bucketExists(bucketName);
            if (!flag) {
                return true;
            }
        }
        return false;
    }

    /**
     * 列出存储桶中的所有对象名称
     *
     * @param bucketName
     * @return
     */
    @SneakyThrows
    public List<String> listObjectNames(String bucketName) {
        List<String> listObjectNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<Item>> myobjects = listObjects(bucketName);
            for (Result<Item> result : myobjects) {
                Item item = result.get();
                listObjectNames.add(item.objectName());
            }
        }
        return listObjectNames;
    }

    /**
     * 列出存储桶中所有对象
     *
     * @param bucketName
     * @return
     */
    @SneakyThrows
    public Iterable<Result<Item>> listObjects(String bucketName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            return minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
        }
        return null;
    }

    /**
     * 返回文件访问路径
     *
     * @param bucketName
     * @param file
     * @param filename
     * @return
     */
    @SneakyThrows
    public String putObject(String bucketName, MultipartFile file, String filename) {
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        filename += fileSuffix;
        PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(filename)
                .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
        //文件名称相同会覆盖
        minioClient.putObject(objectArgs);
        return url + "/" + bucketName + "/" + filename;
    }

    /**
     * 返回文件访问路径
     *
     * @param file
     * @param filename
     * @return
     */
    @SneakyThrows
    public String putObject(MultipartFile file, String filename) {
        String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        filename += fileSuffix;
        PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucket).object(filename)
                .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
        //文件名称相同会覆盖
        minioClient.putObject(objectArgs);
        return url + "/" + bucket + "/" + filename;
    }

    /**
     * 移除文件
     * @param bucketName
     * @param objectName
     * @return
     */
    @SneakyThrows
    public boolean removeObject(String bucketName,String objectName){
        boolean flag = bucketExists(bucketName);
        if (flag){
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
            return true;
        }
        return false;
    }
}
